package http

import (
	"awesomeTask/commom/addrHelper"
	"awesomeTask/commom/timeHelper"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	log2 "awesomeTask/system/log"
	"awesomeTask/system/resource"
	"net/http"
	"reflect"
	"strconv"
	"strings"
)

type HttpServerObj struct {
	IpAddress string
	Port      float64
	addr      *string
	modules   map[string]func() HttpHandler
}
type HttpServer interface {
}

func (server *HttpServerObj) hander(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
	//w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型
	//w.Header().Set("content-type", "application/json")
	//w.Header().Add("access-control-allow-headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma,Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,sec-ch-ua,sec-ch-ua-mobile,User-Agent,Accept")
	//if r.Header.Get("Origin") != "" {
	//	w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("Origin"))
	//	w.Header().Add("Access-Control-Allow-Credentials", "true")
	//} else {
	//	w.Header().Add("Access-Control-Allow-Origin", r.Header.Get("*"))
	//}
	//w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	//w.Header().Set("content-type", "application/json")             //返回数据格式是json
	//w.Header().Set("Content-Type", "application/json; charset=utf-8")
	////允许访问所有域
	w.Header().Add("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,PATCH,OPTIONS")
	defer func() {
		if r := recover(); r != nil {
			w.WriteHeader(500)
			w.Header().Add("Access-Control-Allow-Origin", "*") //允许访问所有域
			w.Write([]byte(helper.JsonEncode(map[string]interface{}{
				"code": 500,
				"msg":  "awesomeTask 无法处理此请求",
			})))
			log2.GetLogger().Error(helper.PrintStackTrace(r.(error)))
			return
		}
	}()
	startAt := timeHelper.NowFloat()
	route := strings.Split(r.URL.String(), "?")[0]
	moduleInfo := strings.Split(route, "/")
	action := moduleInfo[len(moduleInfo)-1]
	module := strings.ReplaceAll(route, action, "")
	action = strings.Title(action)
	if handlerFun, ok := server.modules[module]; ok {
		handler := handlerFun()
		handler.SetHttpInfo(w, r)
		handler.InitRequest()
		ioc := kernel.GetIocInstance()
		res := ioc.CallFunByName(handler, "Action"+action).([]reflect.Value)
		if len(res) > 0 {
			responseValue := res[0].Interface()
			switch responseValue.(type) {
			case string:
				w.Write([]byte(responseValue.(string)))
				break
			case []byte:
				w.Write(responseValue.([]byte))
				break
			case map[string]interface{}:
				if _, ok := responseValue.(map[string]interface{})["code"]; !ok {
					responseValue.(map[string]interface{})["code"] = 200
					responseValue.(map[string]interface{})["pTime"] = timeHelper.NowFloat() - startAt
				}
				w.Write([]byte(helper.JsonEncode(responseValue)))
				break
			default:
				w.Write([]byte(helper.JsonEncode(responseValue)))
				break
			}
		}

	} else {
		url := r.URL.String()
		if url == "/" || url == "" {
			url = "/index.html"
		}
		asbPath, err := resource.GetResourceManager().FindAbsPath("web" + r.URL.String())
		if err == nil {
			http.ServeFile(w, r, asbPath)
			return
		}
		w.WriteHeader(404)
		w.Write([]byte(helper.JsonEncode(map[string]interface{}{
			"code": 400,
			"msg":  "awesomeTask 无法处理此请求",
		})))
	}
}
func (httpServerObj *HttpServerObj) Listen() HttpServer {
	httpServerObj.addr = addrHelper.BuildAddr(httpServerObj.IpAddress, httpServerObj.Port)
	log2.GetLogger().Info("启动http服务:" + httpServerObj.IpAddress + strconv.Itoa(int(httpServerObj.Port)))
	http.HandleFunc("/", httpServerObj.hander)
	return httpServerObj
}

func (httpServerObj *HttpServerObj) RegisterModule(getHandlerFun func() HttpHandler) HttpServerObj {
	if httpServerObj.modules == nil {
		httpServerObj.modules = make(map[string]func() HttpHandler)
	}
	httpServerObj.modules[getHandlerFun().GetModuleName()] = getHandlerFun
	return *httpServerObj
}
